import { FootToolbar } from '@/components/footToolbar';
import React, { useEffect, useRef, useState } from 'react';
import { Card, Avatar } from 'antd';
import  styles from'./index.less';
import {
  LogoutOutlined
} from '@ant-design/icons';
import { Modal, udp, useAsyncEffect } from '@cscec/udp-mobile-ui';
import Toast from 'antd-mobile/es/components/toast';
import { Button, Form, Input, List } from 'antd-mobile';
import { EditSOutline, LockOutline } from 'antd-mobile-icons';
import BellaHeader from '@/components/header';
import { getUserdetail, saveOrUpdate, updatePassWord } from './service';
import Upload, { UploadProps } from 'antd/es/upload/Upload';
import { GetProp } from 'antd/lib/_util/type';
import message from 'antd/lib/message';
import PointsCard from './components/PointsCard';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

export interface PasswordForm {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}
const PageList: React.FC = () => {
    const [studentInfo, setStudentInfo] = useState<any>({
    userCode: '20240512001',
    userName: '李明轩',
    phone: '13812345678',
    imgUrl: 'https://picsum.photos/seed/student/200/200',
    classes: ['KB1-实验班', 'KB2-提高班'],
  });

  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [pwdModalVisible, setPwdModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [pwdForm] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  // const userData:any = localStorage.getItem('__login_info__')
  //  useEffect(()=>{
  //   setStudentInfo(JSON.parse(userData))
  //  },[])
   useAsyncEffect(async ()=>{
    const res = await getUserdetail()
    //console.log(res)
    setStudentInfo(res)
   },[])
  // console.log(udp.CryptoJS.encode('12345678'))//加密
  // console.log(udp.CryptoJS.decode('e57b049f3836b4205ae8fa35b60d69f1'))//解密
  // 提交个人信息表单
  const handleInfoSubmit = async () => {
    try {
      const values = await form.validateFields();
      const parm = {...studentInfo,...values}
      const res:any = await saveOrUpdate(parm)
     // console.log(parm)
      if(res.code==200){
        setStudentInfo(parm);
        localStorage.setItem('__login_info__', JSON.stringify(parm));
        setInfoModalVisible(false);
        Toast.show('信息修改成功');
      }else {
        Toast.show(res.message);
      }
    } catch (error) {
      console.log('表单验证失败:', error);
    }
  };

  // 提交密码修改表单
  const handlePwdSubmit = async () => {
    try {
      const values = await pwdForm.validateFields();
      if (values.newPassword !== values.confirmPassword) {
        Toast.show('两次输入的密码不一致');
        return;
      }
      // 这里应该是调用API修改密码
      const res:any =await updatePassWord({
        id:studentInfo.id,
        newPassword:udp.CryptoJS.encode(values.newPassword),//加密
        oldPassword:udp.CryptoJS.encode(values.oldPassword)
      })
      if(res.code==200){
      setPwdModalVisible(false);
        Toast.show('密码修改成功');
      }else{
        Toast.show(res.message);
      }
    } catch (error) {
      console.log('密码表单验证失败:', error);
    }
  };

  // 退出登录
  const handleLogout = () => {
    Modal.show({
      content: '确定要退出登录吗？',
      closeOnAction: true,
      actions:[
        {
          key: 'cancel',
          text: '取消',
        },
        {
          key: 'confirm',
          style:{backgroundColor:"#1eb7d8",borderRadius:'30px'},
          text: '确定',
          primary: true,
          onClick:() => {
            Toast.show('已退出登录');
            //跳转到登录页面
            setTimeout(() => {
              localStorage.clear()
              window.location.href = '#';
            }, 500);
          },
        },
      ]
    });
  };

  const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('仅支持上传JPG/PNG文件类型的图片!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!');
  }
  return isJpgOrPng && isLt2M;
};

  const handleChange: UploadProps['onChange'] = async (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      console.log(info.file);
      const { code, data, message } = info.file.response;
      console.log(data);
       const param = {...studentInfo,imgUrl: data.url}
      const res:any = await saveOrUpdate(param)
      if(res.code==200){
        setStudentInfo(param);
        localStorage.setItem('__login_info__', JSON.stringify(param));
        Toast.show('头像修改成功');
      }else{
         Toast.show(res.message);
      }
      setLoading(false);
    }
  };


  return (
    <div className="page-outer">
      <div className={styles["student-profile"]}>
      {/* 顶部导航 */}
      <BellaHeader title={'个人中心'}  onMain={() => { udp.open('/BellaEnglish') }} />
      {/* 主内容区 */}
      <div className={styles["profile-content"]}>
        {/* 头像和基本信息卡片 */}
        <Card className={styles["info-card"]}>
          <div className={styles["avatar-section"]}>
              <Upload
              name="file"
              listType="picture-circle"
              className={styles["Upload"]}
              showUploadList={false}
              action="/api/minio/uploadImage?fileType=0"
              beforeUpload={beforeUpload}
              onChange={handleChange}
              headers={{
                'user-token': udp.getUser().accessToken
              }}
            >
            <Avatar  src={studentInfo.imgUrl} className={styles["avatar-img"]} /> 
            </Upload>
            <div className={styles["basic-info"]}>
              <h2 className={styles["student-name"]}>{studentInfo.userName}</h2>
              <p className={styles["student-id"]}>学号：{studentInfo.userCode}</p>
            </div>

            {/* <div className={styles["classes-tags"]}>
              {studentInfo.classes?studentInfo.classes.map((cls, index) => (
                <span key={index} className={styles["class-tag"]}>
                  {cls}
                </span>
              )):''}
            </div> */}
            <PointsCard points={studentInfo.totalScore} />
            <Button
              className={styles["edit-btn"]}
              fill="solid"
              color="primary"
              onClick={() => setInfoModalVisible(true)}
            >
              <EditSOutline className={styles["edit-icon"]} />
              编辑信息
            </Button>
          </div>
        </Card>

        {/* 功能选项列表 */}
        <List className={styles["function-list"]}>
          <List.Item
            prefix={<LockOutline className={styles["list-icon"]} />}
            arrow={<div className={styles["arrow-icon"]}>›</div>}
            onClick={() => setPwdModalVisible(true)}
          >
            修改密码
          </List.Item>
          
          <List.Item
            prefix={<LogoutOutlined 
              //className="list-icon logout-icon" 
              className={styles["list-icon"]}
            />}
            arrow={<div className={styles["arrow-icon"]}>›</div>}
            onClick={handleLogout}
            className={styles["logout-item"]}
          >
            <span style={{color:'#ff4d4f'}} className={styles["logout-text"]}>退出登录</span>
          </List.Item>
        </List>
      </div>
    </div>
       <FootToolbar/>
      {/* 编辑信息弹窗 */}
      <Modal
        visible={infoModalVisible}
        title="编辑个人信息"
        content={
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              userName: studentInfo.userName,
              userCode: studentInfo.userCode,
              phone: studentInfo.phone,
            }}
          >
            <Form.Item
              name="userName"
              label="姓名"
              rules={[{ required: true, message: '请输入姓名' }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
            
            <Form.Item
              name="userCode"
              label="学号"
            >
              <Input placeholder="学号" readOnly />
            </Form.Item>
            
            <Form.Item
              name="phone"
              label="手机号码"
              rules={[
                { required: true, message: '请输入手机号码' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
              ]}
            >
              <Input placeholder="请输入手机号码" maxLength={11} />
            </Form.Item>
          </Form>
        }
        closeOnAction
        onClose={() => setInfoModalVisible(false)}
        actions={[
          {
            key: 'cancel',
            text: '取消',
          },
          {
            key: 'confirm',
            style:{backgroundColor:"#1eb7d8",borderRadius:'30px'},
            text: '保存',
            primary: true,
            onClick: handleInfoSubmit,
          },
        ]}
      />

      {/* 修改密码弹窗 */}
      <Modal
        visible={pwdModalVisible}
        title="修改密码"
        content={
          <Form form={pwdForm} layout="vertical">
            <Form.Item
              name="oldPassword"
              label="原密码"
              rules={[{ required: true, message: '请输入原密码' }]}
            >
              <Input type="password" placeholder="请输入原密码" />
            </Form.Item>
            
            <Form.Item
              name="newPassword"
              label="新密码"
              rules={[
                { required: true, message: '请输入新密码' },
                { min: 6, message: '密码长度至少6位' },
              ]}
            >
              <Input type="password" placeholder="请输入新密码" />
            </Form.Item>
            
            <Form.Item
              name="confirmPassword"
              label="确认新密码"
              rules={[{ required: true, message: '请确认新密码' }]}
            >
              <Input type="password" placeholder="请确认新密码" />
            </Form.Item>
          </Form>
        }
        closeOnAction
        onClose={() => setPwdModalVisible(false)}
        actions={[
          {
            key: 'cancel',
            text: '取消',
          },
          {
            key: 'confirm',
            text: '确认修改',
            style:{backgroundColor:"#1eb7d8",borderRadius:'30px'},
            primary: true,
            onClick: handlePwdSubmit,
          },
        ]}
      />
    </div>
  );
};

export default PageList;
